class User < ApplicationRecord
    has_many :posts, dependent: :destroy
    has_many :comments, dependent: :destroy
    attr_accessor :remember_token, :activation_token
    before_save :downcase_email
    before_create :create_activation_digest
    validates :name, presence: { message: '用户名不能为空！' }, length: { maximum: 64 ,message: '用户名过长'},uniqueness: { message: '用户名已存在！' }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    before_save { self.email = email.downcase }
    validates :email, presence: { message: '邮箱不能为空！' },  length: { maximum: 255 ,message: '邮箱过长'},
    format: { with: VALID_EMAIL_REGEX ,message: '不符合邮箱格式！'},
    uniqueness: { message: '邮箱已存在！' }
    has_secure_password
    validates :password, presence: { message: '密码不能为空！' }, length: { minimum: 6 ,message: '密码过短，至少6位！'} , allow_nil: true


    def User.digest(string)
        cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
        BCrypt::Password.create(string, cost: cost)
    end
    def User.new_token
        SecureRandom.urlsafe_base64
    end
    def authenticated?(attribute, token)
        digest = send("#{attribute}_digest")
        return false if digest.nil?
        BCrypt::Password.new(digest).is_password?(token)
    end
    private
    def downcase_email
        self.email = email.downcase
    end
    def create_activation_digest
        self.activation_token = User.new_token
        self.activation_digest = User.digest(activation_token)
    end
end
